package com.atguigu.cloud.service.impl;

import com.atguigu.cloud.apis.AccountFeignApi;
import com.atguigu.cloud.apis.StorageFeignApi;
import com.atguigu.cloud.entities.Order;
import com.atguigu.cloud.mapper.OrderMapper;
import com.atguigu.cloud.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

//    订单微服务通过openfeign调用storage微服务和account微服务
    @Resource
    private StorageFeignApi storageFeignApi;
    @Resource
    private AccountFeignApi accountFeignApi;
    @Override
    @GlobalTransactional(name = "zzyy-create-order",rollbackFor = Exception.class)   // 开启分布式事务
    public void create(Order order) {
//        xid全局事务id的检查  ---- 重要
        String xid = RootContext.getXID();
//        1.新建订单
        log.info("---------------新建订单"+"xid:"+xid);
        order.setStatus(0);
        int i = orderMapper.insertSelective(order);
//        插入完成后获得插入mysql的实体对象
        Order orderFromDB = null;
        if (i >0){
            orderFromDB = orderMapper.selectOne(order);
            log.info("-------------------> 新建成功，orderFromDB:"+orderFromDB);
            System.out.println();
//           2.扣减库存
            log.info("---------------开始扣减库存"+"xid:"+xid);
            storageFeignApi.decrease(orderFromDB.getProductId(),orderFromDB.getCount());
            log.info("---------------结束扣减库存"+"xid:"+xid);
            System.out.println();
//            3.扣减余额
            log.info("---------------开始扣减余额"+"xid:"+xid);
            accountFeignApi.decrease(orderFromDB.getUserId(),orderFromDB.getMoney());
            log.info("---------------结束扣减余额"+"xid:"+xid);
            System.out.println();
//            修改订单状态  --- 将订单状态从0改成1
            log.info("---------------开始修改订单状态"+"xid:"+xid);
            orderFromDB.setStatus(1);
            Example example = new Example(Order.class);
            Example.Criteria criteria =  example.createCriteria();
            criteria.andEqualTo("userId",orderFromDB.getUserId());
            criteria.andEqualTo("status",0);
            int updateResult = orderMapper.updateByExampleSelective(orderFromDB, example);
            log.info("---------------结束修改订单状态"+"xid:"+xid);
            System.out.println();
        }
        System.out.println();
        log.info("---------------结束新建订单"+"xid:"+xid);

    }
}
